package cn.com.dhc.danlu.activity.envelope;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import cn.com.dhc.danlu.R;
import cn.com.dhc.danlu.activity.DefaultFragmentActivity;
import cn.com.dhc.danlu.fragment.EnvelopFragment.OnSelectEnvelop;
import cn.com.dhc.danlu.util.CalculatePriceUtil;
import cn.com.dhc.danlu.util.CommonUtils;
import cn.com.dhc.danlu.util.ToastUtil;
import cn.com.dhc.danlu.widget.DLToolbar;
import cn.com.dhc.danlu.widget.PagerSlidingTabStrip;
import cn.com.dhc.danlu.widget.adapter.EnvelopeFragmentAdapter;
import cn.com.hd.mall.web.webservices.entity.response.cpx.GetCouponListResponse.CouponListModel;

/**
 * @author wuhaiyang
 */
public class EnvelopeableActivity extends DefaultFragmentActivity implements OnSelectEnvelop {
    /**
     * 维护当前用户选中的红包个数
     */
    private final ArrayList<CouponListModel> mSelectEnvelops = new ArrayList<>();
    //    private DanluTaskProxy danluTaskProxy;
    private int maxTicketUseNum;
    private String mHighestDeduction;
    private DLToolbar mToolbar;
    private PagerSlidingTabStrip mPagerSlidingTabStrip;
    private ViewPager mViewPager;

    private TextView tvDeduction;
    private TextView tvHasUsed;
    private Button btnConfirm;

    //    @Override
    //    public DanluTaskProxy getDanluTaskProxy() {
    //        return danluTaskProxy;
    //    }

    @Override
    public void onSelect(CouponListModel obj, boolean isAdd) {
        if (isAdd) {
            // 添加一个红包到数组中
            mSelectEnvelops.add(obj);
        } else {
            // 从数组中移除指定的红包
            boolean remove = mSelectEnvelops.remove(obj);
            //所有红包价值面额
            BigDecimal totalUseEvelop = getTotalUseEvelop();
            int compare = CalculatePriceUtil.compare(totalUseEvelop.toPlainString(), mHighestDeduction);
            String couponAmt = obj.getCouponAmt();
            for (CouponListModel model : mSelectEnvelops) {
                if (CalculatePriceUtil.compare(model.getFactUse(), model.getCouponAmt()) != 0) {
                    BigDecimal addition = CalculatePriceUtil.addition(model.getFactUse(), couponAmt);
                    if (compare == -1 || compare == 0) {
                        // 小于|等于
                        model.setFactUse(model.getCouponAmt());
                    } else {
                        model.setFactUse(addition.toPlainString());
                    }
                    break;
                }
            }
        }
        // 更新底部数量显示
        refreshBottomCouponShow();
    }

    @Override
    public String getCacheJsonStr() {
        Bundle extras = getIntent().getExtras();
        return extras.getString("envelop_json");
    }

    @Override
    public List<CouponListModel> getLastSelect() {
        return mSelectEnvelops;
    }

    @Override
    public boolean isBeyondUseCouponConditions(CouponListModel couponListModel) {
        if (mSelectEnvelops.size() >= maxTicketUseNum) {
            ToastUtil.getInstance().show("使用红包张数不能超过" + maxTicketUseNum);
            return true;
        }
        BigDecimal totalUseBd = getTotalUseEvelop();
        int compare = CalculatePriceUtil.compare(totalUseBd.toPlainString(), mHighestDeduction);
        if (compare == 1 || compare == 0) {
            String maxYuan = CommonUtils.formateRate(CommonUtils.fenToYuan(new BigDecimal(mHighestDeduction)).toPlainString());
            ToastUtil.getInstance().show("使用红包金额不能超过" + maxYuan + "元");
            return true;
        }
        totalUseBd = CalculatePriceUtil.addition(totalUseBd.toPlainString(), couponListModel.getCouponAmt());
        //再次比较
        int compare2 = CalculatePriceUtil.compare(totalUseBd.toPlainString(), mHighestDeduction);
        if (compare2 == 1) {
            //  红包面额大于或者等于 最大价格
            BigDecimal vacancyBd = CalculatePriceUtil.subtraction(totalUseBd.toPlainString(), mHighestDeduction);
            BigDecimal useBd = CalculatePriceUtil.subtraction(couponListModel.getCouponAmt(), vacancyBd.toPlainString());
            //暂时没有处理小数情况
            couponListModel.setFactUse(useBd.toPlainString());
        } else {
            couponListModel.setFactUse(couponListModel.getCouponAmt());
        }
        return false;
    }

    private BigDecimal getTotalUseEvelop() {
        BigDecimal bdTotal = new BigDecimal(0);
        for (int i = 0; i < mSelectEnvelops.size(); i++) {
            bdTotal = CalculatePriceUtil.addition(bdTotal.toPlainString(), mSelectEnvelops.get(i).getCouponAmt());
        }
        return bdTotal;
    }

    @SuppressLint("SetTextI18n")
    private void refreshBottomCouponShow() {
        BigDecimal deductionBd = CommonUtils.fenToYuan(getTotalUseEvelop());
        tvHasUsed.setText("￥" + CommonUtils.formateRate(deductionBd.toPlainString()));
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_envelopable);
        initView();
        Bundle extras = getIntent().getExtras();
        mHighestDeduction = extras.getString("mHighestDeduction");

        BigDecimal decimal = CommonUtils.fenToYuan(new BigDecimal(mHighestDeduction));
        tvDeduction.setText("￥" + CommonUtils.formateRate(decimal.toPlainString()));

        maxTicketUseNum = extras.getInt("maxTicketUseNum");
        ArrayList<CouponListModel> lastSelect = (ArrayList<CouponListModel>) extras.getSerializable("lastselect");
        if (null != lastSelect && !lastSelect.isEmpty()) {
            mSelectEnvelops.addAll(lastSelect);
            // 刷新底部金额
            refreshBottomCouponShow();
        }
        EnvelopeFragmentAdapter pagerAdapter = new EnvelopeFragmentAdapter(getSupportFragmentManager(), EnvelopeFragmentAdapter.TYPE_ENVELOP_USE);
        mViewPager.setAdapter(pagerAdapter);
        mPagerSlidingTabStrip.setViewPager(mViewPager);
        mPagerSlidingTabStrip.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
            }
        });
        btnConfirm.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                commitLogic();
            }
        });
        mToolbar.setRightClickListenter(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(EnvelopeableActivity.this, InstructionAndRuleActivity.class);
                startActivity(intent);
            }
        });
    }

    //    @Override
    //    public AsyncTaskActivityDelegate getDelegate() {
    //        return delegate;
    //    }

    private void initView() {
        mToolbar = (DLToolbar) findViewById(R.id.toolbar);
        mPagerSlidingTabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        mViewPager = (ViewPager) findViewById(R.id.view_pager);
        tvDeduction = (TextView) findViewById(R.id.tv_deduction);
        tvHasUsed = (TextView) findViewById(R.id.tv_has_used);
        btnConfirm = (Button) findViewById(R.id.btn_confirm);
    }

    protected void commitLogic() {
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putSerializable("select", mSelectEnvelops);
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
        finish();
    }
}